package com.iyimo.util
{
	import com.iyimo.i.ITimeLogic;
	
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	public final class TimeMachine{
		private static const INTERVAL_MS:Number = 1000;
		private static var instance:TimeMachine = new TimeMachine();
		
		private var _timeLogicVector:Vector.<ITimeLogic>;
		private var _timer:Timer;
		
		public function TimeMachine(){
			_timeLogicVector = new Vector.<ITimeLogic>();
			
			_timer = new Timer(INTERVAL_MS);
			_timer.addEventListener(TimerEvent.TIMER, update);
			_timer.start();
		}
		
		public static function startTimer(condition:ITimeLogic):void{
			var allLogic:Vector.<ITimeLogic> = instance._timeLogicVector;
			
			var index:int = allLogic.indexOf(condition);
			if (index == -1)
				allLogic.push(condition);
		}
		
		public static function endTimer(condition:ITimeLogic):void{
			var allLogic:Vector.<ITimeLogic> = instance._timeLogicVector;
			
			var index:int = allLogic.indexOf(condition);
			if (index != -1)
				allLogic.splice(index, 1);
		}
		
		private function update(event:TimerEvent):void{
			for each (var logic:ITimeLogic in this._timeLogicVector)
				logic && logic.onTimer();
		}
	}
}